<?php


namespace support\exception;


use Throwable;
use Webman\Exception\ExceptionHandler;
use Webman\Http\Request;
use Webman\Http\Response;

class ApiHandler extends ExceptionHandler
{
    public $dontReport = [
        BadException::class,
    ];

    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    public function render(Request $request, Throwable $exception): Response
    {
        if (($exception instanceof BadException) && ($response = $exception->render($request))) {
            return $response;
        }

        $code = $exception->getCode();
        if ($request->expectsJson()) {
            $json = [
                'code' => $code ?: 500,
                'msg' => $this->debug ? $exception->getMessage() : 'Server internal error',
            ];
            $this->debug && $json['traces'] = explode("\n", $exception->getTraceAsString());
            return new Response(200, ['Content-Type' => 'application/json'],
                json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        }
        $error = $this->debug ? nl2br((string)$exception) : 'Server internal error';
        return new Response(500, [], $error);
    }

}